package com.crack.nga2.volley;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.crack.nga2.utils.DataUtil;
import com.crack.nga2.utils.GlobalConst;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 回帖、发帖等预置步骤
 * Created by Administrator on 2016/1/7.
 */
public class PostRequestStep1 extends Request<Map<String, String>> {
    private Response.Listener<Map<String, String>> listener;

    public PostRequestStep1(int method, String url, Response.Listener<Map<String, String>> listener, Response.ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> map = new HashMap<>();
        map.put("Cookie", GlobalConst.Cookie);
        return map;
    }

    @Override
    protected Response<Map<String, String>> parseNetworkResponse(NetworkResponse response) {
        String json;
        try {
            json = new String(response.data, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return Response.error(new VolleyError(e.getMessage()));
        }
        Map<String, String> map = new HashMap<>();
        Log.i("tag",json);
        json = DataUtil.getData(json);
        JSONObject object;
        try {
            object = new JSONObject(json);
            if (json.contains("content")) {
                String content = object.getString("content");
                Log.i("tag",content);
                map.put("content", content);
            }
            if (json.contains("auth")) {
                String auth = object.getString("auth");
                Log.i("tag",auth);
                map.put("auth", auth);
            }
            if (json.contains("attach_url")) {
                String attach_url = object.getString("attach_url");
                Log.i("tag",attach_url);
                map.put("attach_url", attach_url);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return Response.error(new VolleyError(e.getMessage()));
        }

        return Response.success(map, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(Map<String, String> response) {
        if (listener != null) {
            listener.onResponse(response);
        }
    }
}
